import cookies from 'js-cookie'
import ManageConstant from "../consts/manageConstant";
import qs from "qs"

class PermissionService{
  constructor(_this) {
    this._this = _this;
    this._axios = _this.axios.create({
      baseURL: ManageConstant.DOMAIN_URL,
      timeout: 5000,
      headers: {
        Token: cookies.get('Token')
      }
    });
  }

  searchPermission(params, executeMethod){
    this._axios.get(ManageConstant.PERMISSION_SEARCH, {params}).then(res => {
      if (res.data.resultCode == 0) {
        executeMethod(this._this, res.data);
        // console.log(res.data.page.total);
      }
    })
  }

  addPermission(params){
    this._axios.post(ManageConstant.PERMISSION_ADD, params).then(res => {
      if (res.data.resultCode == 0) {
        this._this.$Message.success("添加权限成功");
        this._this.resetFormData();
        this._this.searchPermission(0,10,'');
      }
      else if(res.data.resultCode == 1011){
        this._this.$Message.error("权限已存在");
      }
      else{
        this._this.$Message.error("添加失败");
      }
    })
  }

  editPermission(params){
    this._axios.post(ManageConstant.PERMISSION_EDIT, params).then(res => {
      if (res.data.resultCode == 0) {
        this._this.$Message.success("修改权限成功");
        this._this.resetFormData();
        this._this.searchPermission(0,10,'');
      }
      else{
        this._this.$Message.error("修改失败");
      }
    })
  }

  getPermissionsByRole(params, executeMethod){
    this._axios.get(ManageConstant.ROLE_GET_PERMISSION, {params}).then(res => {
      if (res.data.resultCode == 0) {
        executeMethod(this._this, res.data);
        // console.log(res.data.page.total);
      }
    })
  }

  assignPermissions(params){
    this._axios.post(ManageConstant.ROLE_SET_PERMISSION, params).then(res => {
      if (res.data.resultCode == 0) {
        this._this.$Message.success("分配权限成功");
        this._this.resetFormData();
      }
      else{
        this._this.$Message.error("分配失败");
      }
    })
  }

  //注意使用qs传数组数据，参数名要与文档要求参数名一致如下permisssionIds
  batchDeletePermissions(permissionIds){
    this._axios.post(ManageConstant.PERMISSION_BATCH_DELETE, qs.stringify({
      permissionIds
    }, {
      indices: false
    })).then(res => {
      if (res.data.resultCode == 0) {
        this._this.$Message.success("删除权限成功");
        this._this.resetFormData();
        this._this.searchPermission(0,10,'');
      }
      else{
        this._this.$Message.error("删除失败");
      }
    })
  }
}

export default PermissionService;
